package entities;

import com.liquidcode.cellular.Texture;

public class CAnimatedSprite extends CSprite
{
	private int MAX_FRAMES = 0;
	private int MAX_ROW = 0;
	private int MAX_COL = 0;
	private int m_currentRow = 0;
	private int m_currentCol = 0;
	// timer variables 
	private float m_currTime = 0.0f; 
	private float m_animationTime = 0.0f;
	// frame size variables 
	private float m_frameWidth = 0.0f;
	private float m_frameHeight = 0.0f;
	private boolean m_looping = false;
	private boolean m_done = false;
	
	
	public CAnimatedSprite(int maxFrames, int rows, int cols, float frameWidth, float frameHeight, float animTime, boolean looping)
	{
		MAX_FRAMES = maxFrames;
		MAX_ROW = rows;
		MAX_COL = cols;
		m_frameWidth = frameWidth;
		m_frameHeight = frameHeight;
		m_animationTime = animTime;
		m_looping = looping;
	}
	
	
	@Override 
	public void Update(float dt)
	{
		// update the animation time 
		m_currTime += dt; 
		
		// if its ready to be updated 
		if( m_currTime >= m_animationTime && m_done == false )
		{
			m_currTime = 0.0f;
			// now check the row and columns 
			if( m_currentCol < (MAX_COL-1) )
			{
				m_currentCol += 1;
			}
			else // we hit the last column reset to 0 and update the row (go down) 
			{
				m_currentCol = 0;
				
				// if we are looping and the row is >= to max_row then just reset the row, 
				// otherwise set the done flag to true 
				if( m_currentRow >= (MAX_ROW-1) )
				{
					if( m_looping == true )
					{
						m_currentRow = 0;
					}
					else
					{
						m_done = true;
					}
				}
				else
				{
					m_currentRow += 1;
				}
			}			
		}
		
		// put the new uv's back in 
		// scroll the uv's		
		 float nwidth = (float)m_frameWidth / (float)width;
	     float nheight = (float)m_frameHeight / (float)height;
	     float u = (float)(m_currentCol*m_frameWidth) / (float)width;
	     float v = (float)(m_currentRow*m_frameHeight) / (float)height;
		
		mTextureBuffer.put(0, u);
		mTextureBuffer.put(2, u+nwidth);
		mTextureBuffer.put(4, u);
		mTextureBuffer.put(6, u+nwidth);

		mTextureBuffer.put(1, 1.0f - v);
		mTextureBuffer.put(3, 1.0f - v);
		mTextureBuffer.put(5, (v+nheight) - m_currentRow);
		mTextureBuffer.put(7, (v+nheight) - m_currentRow);
		
		
	}
	
	
	public void setAnimTexture( Texture t )
	{
		if( t != null )
		{
			mTextureID = t.id;
			setWidth(t.width);
			setHeight(t.height);
			SetUpQuad(m_frameWidth, m_frameHeight);
	
		}
	}
	
	// accessors 
	public float getFrameWidth() {
		return m_frameWidth;
	}
	
	public float getFrameHeight() {
		return m_frameHeight;
	}
	
}
